<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="clearfix">
          <span>章节管理</span>
          <el-button
            style="float: right; margin-left: 10px"
            type="primary"
            @click="handleCreate"
          >
            新增章节
          </el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        label-width="68px"
        class="query-form"
      >
        <el-form-item label="章节名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入章节名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="课程" prop="courseId">
          <el-select
            v-model="queryParams.courseId"
            placeholder="请选择课程"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="item in courseOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="chapterList"
        border
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="章节名称" />
        <el-table-column prop="courseName" label="所属课程" />
        <el-table-column prop="sort" label="排序" />
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              link
              @click="handleUpdate(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="small"
              type="primary"
              link
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改章节对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="open"
      width="500px"
      append-to-body
    >
      <el-form ref="chapterForm" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="章节名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入章节名称" />
        </el-form-item>
        <el-form-item label="所属课程" prop="courseId">
          <el-select v-model="form.courseId" placeholder="请选择课程" clearable>
            <el-option
              v-for="item in courseOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="form.sort"
            :min="0"
            controls-position="right"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import {
  getChapterPage,
  getChapterById,
  saveOrUpdateChapter,
  deleteChapter
} from '@/api/chapter'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatDate } from '@/utils/date'

// 页面加载状态
const loading = ref(false)
// 总条数
const total = ref(0)
// 章节列表
const chapterList = ref([])
// 弹窗状态
const open = ref(false)
// 弹窗标题
const dialogTitle = ref('')
// 课程选项
const courseOptions = ref([])

// 表单参数
const form = reactive({
  id: undefined,
  name: '',
  courseId: '',
  sort: 0
})

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  courseId: ''
})

// 表单校验规则
const rules = {
  name: [{ required: true, message: '章节名称不能为空', trigger: 'blur' }],
  courseId: [{ required: true, message: '请选择所属课程', trigger: 'blur' }]
}

// 查询章节列表
const getList = async () => {
  loading.value = true
  try {
    const response = await getChapterPage(queryParams)
    chapterList.value = response.data.records
    total.value = response.data.total
  } catch (error) {
    ElMessage.error('获取章节列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.name = ''
  queryParams.courseId = ''
  queryParams.pageNum = 1
  getList()
}

// 新增章节
const handleCreate = () => {
  dialogTitle.value = '添加章节'
  open.value = true
  resetForm()
}

// 修改章节
const handleUpdate = async (row) => {
  try {
    const response = await getChapterById(row.id)
    Object.assign(form, response.data)
    dialogTitle.value = '修改章节'
    open.value = true
  } catch (error) {
    ElMessage.error('获取章节信息失败')
  }
}

// 提交表单
const submitForm = () => {
  // 校验表单
  // 这里需要获取表单实例进行校验
  saveOrUpdateChapter(form)
    .then(() => {
      ElMessage.success('保存成功')
      open.value = false
      getList()
    })
    .catch(() => {
      ElMessage.error('保存失败')
    })
}

// 取消
const cancel = () => {
  open.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  form.id = undefined
  form.name = ''
  form.courseId = ''
  form.sort = 0
}

// 删除章节
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确认删除章节"${row.name}"吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(() => deleteChapter(row.id))
    .then(() => {
      ElMessage.success('删除成功')
      getList()
    })
    .catch(() => {})
}

// 获取课程选项数据
const getCourseOptions = async () => {
  // 这里需要调用相应的API获取选项数据
  // 暂时使用模拟数据
  courseOptions.value = [
    { id: 1, name: 'Java程序设计' },
    { id: 2, name: 'Python数据分析' }
  ]
}

// 初始化
onMounted(() => {
  getList()
  getCourseOptions()
})
</script>

<style scoped>
.query-form {
  margin-bottom: 20px;
}
</style>